package com.senven.books.modules.system.login.controller;

import com.senven.books.framework.web.model.LoginBody;
import com.senven.books.modules.system.log.annotation.SysLogInfo;
import com.senven.books.modules.system.log.util.LogResultType;
import com.senven.books.modules.system.log.util.LogOptType;
import com.senven.books.modules.system.login.service.LoginService;
import com.senven.books.utils.ResultEnum;
import com.senven.books.utils.ResultVO;
import com.senven.books.utils.ResultVOUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Api(tags = {"登录服务接口"})
@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;


    @ApiOperation(value = "系统登录")
    @PostMapping("/sys/login")
    @SysLogInfo(type = LogOptType.OPT_LOGIN, content = LogResultType.RESULT_SUCCESS)
    public ResultVO login(@RequestBody LoginBody loginBody) {
        ResultVO resultVO = loginService.login(loginBody);
        return resultVO;
    }

    @PostMapping("/sys/logout")
    public ResultVO login() {
        loginService.logout();
        ResultVO resultVO = ResultVOUtil.success(ResultEnum.SUCCESS.getCode(), "注销成功", null);
        return resultVO;
    }

    @PostMapping("/admin")
    @ResponseBody
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public void printAdmin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.print("如果你看见这句话，说明你有ROLE_ADMIN角色");
        out.close();
    }

    @PostMapping("/user")
    @ResponseBody
    @PreAuthorize("hasRole('ROLE_USER')")
    public String printUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        return "如果你看见这句话，说明你有ROLE_USER角色";
    }
}